/**
 * BBD Service Inc
 * All Rights Reserved @2018
 */
package com.magicmovie.web.controller;

import com.alibaba.fastjson.JSON;
import com.magicmovie.entity.Customer;
import com.magicmovie.utils.*;
import com.magicmovie.utils.data.PageModel;
import com.magicmovie.web.service.CustomerService;
import org.apache.shiro.crypto.hash.Sha256Hash;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Map;

/**
 * 輪播管理
 *
 * @author
 */
@Controller
@RequestMapping("/customer")
public class CustomerController {
    @Resource
    private CustomerService customerService;

    @RequestMapping(value = "/list")
    public String list(Model model) {
        return "customers/list";
    }

    @RequestMapping("/query")
    @ResponseBody
    public JqgridPage query(int page, int rows, String sidx, String sord, String filters) {
        QueryFilters filters_ = null;
        if (filters == null || filters.trim().isEmpty()) {
            filters_ = new QueryFilters();
        } else {
            filters_ = JSON.parseObject(filters, QueryFilters.class);
        }
        filters_.setSidx(sidx);
        filters_.setSord(sord);
        filters_.setPageNo(page);
        filters_.setPageSize(rows);
        PageModel pageInfo = customerService.getByFilter(filters_);
        // 用JqgridPage对结果进行包装
        return new JqgridPage((long) pageInfo.getTotalRecord(), pageInfo.getTotalPage(), pageInfo.getPageNo(),
                pageInfo.getResults());
    }

    @RequestMapping("/resetPassword")
    @ResponseBody
    public AjaxMsg resetPassword(String id, HttpServletRequest request) {
        AjaxMsg ajaxMsg = new AjaxMsg();

        if (ValidUtil.isEmpty(id)) {
            ajaxMsg.setMessage("请选择需要重置密码的用户");
            ajaxMsg.setCode(AjaxMsg.FAILURE);
        } else if (id.split(",").length > 1) {
            ajaxMsg.setMessage("同时只可以选择一个用户");
            ajaxMsg.setCode(AjaxMsg.FAILURE);
        } else {
            String password=VerifyCodeGenerator.getRandNum(6);
            Customer customer = customerService.getByPrimaryKey(Integer.parseInt(id));
            customer.setPassword(new Sha256Hash(password,customer.getSalt()).toHex());
            customerService.updateByPrimaryKeySelective(customer);
            ajaxMsg.setCode(AjaxMsg.SUCCESS);
            ajaxMsg.setDatas(password);
        }
        return ajaxMsg;
    }

}
